<template>
    <div class="purchase-container">
        <!-- 物品列表 -->
        <div class="p-item" v-for="(item, index) in column" :key="index">
            <div class="p-top">
                <div class="p-top-left">{{ item.goodsName }}</div>
                <div class="p-top-right">￥{{ item.unitPrice }}/{{ item.goodsUnit }}</div>
            </div>

            <div class="p-text">
                <div class="p-text-line flex jB">
                    <span>申请数量：{{ item.goodsAmount }}</span>
                    <span>金额：{{ item.amount }}</span>
                </div>
                <div style="padding-bottom: 15px;" class="p-text-line flex">备注：{{ item.remark }}</div>
            </div>

            <van-button type="danger" size="small" class="delbtn" @click="deleteTap(index)">删除</van-button>

            <van-button type="primary" size="small" class="editbtn" @click="editTap(index)">编辑</van-button>
        </div>

        <!-- 添加按钮 -->
        <div class="p-add" @click="addTap">+</div>

        <!-- 底部合计和提交 -->
        <div class="bottom-btn">
            <div>
                合计：
                <span class="total">{{ totalMoney }}</span>
            </div>
            <van-button type="primary" block class="submit-btn" :loading="loading"
                @click="submitClick">提交申请</van-button>
        </div>

        <!-- 添加/编辑物品弹窗 -->
        <van-dialog v-model="show" title="添加物品" show-cancel-button @confirm="submitDialogTap" @cancel="cancleDialogTap">
            <div class="add-body">
                <van-field label="类型" readonly :value="categoryName" placeholder="请选择类型"
                    @click="showCategoryPicker = true, keyword = ''" />

                <van-field label="品名" readonly :value="goodsName" placeholder="请选择品名" @click="showGoodsDialog" />

                <van-field label="单位" readonly :value="goodsUnit || '-'" />

                <van-field v-model="unitPrice" label="单价" type="digit" placeholder="请输入单价" maxlength="9" />

                <van-field v-model="goodsAmount" label="数量" type="number" placeholder="请输入数量" maxlength="9" />

                <van-field v-model="remark" label="备注" placeholder="请输入备注" maxlength="10" />
            </div>
        </van-dialog>

        <!-- 类型选择弹窗 -->
        <van-popup v-model="showCategoryPicker" position="bottom">
            <van-picker :columns="categoryList" value-key="categoryName" @confirm="onCategoryConfirm"
                @cancel="showCategoryPicker = false" show-toolbar />
        </van-popup>

        <!-- 品名选择弹窗 -->
        <van-dialog v-model="goodsShow" title="选择品名" show-cancel-button>
            <van-search v-model="keyword" placeholder="请输入关键词" :show-action="false" @input="onSearch" />
            <!-- 联想查询结果列表 -->
            <div class="goods-list-container">
                <van-radio-group class="inline-radio-gruop" v-model="goodsName">
                    <van-cell-group>
                        <van-cell v-for="(item, index) in goodList" :key="index" :title="item.goodsName"
                            @click="goodsSelectTap(item)">
                            <template #right-icon>
                                <van-radio :name="item.goodsName" />
                            </template>
                        </van-cell>
                    </van-cell-group>
                </van-radio-group>
            </div>
        </van-dialog>
    </div>
</template>

<script>
import { Toast } from 'vant'
import { getCategoryList, getGoodsList, submitPurchase, getApplyRecordDetails,purchaseReApply } from '@/api/purchased'

export default {
    name: 'PurchaseControl',

    data() {
        return {
            totalMoney: 0,
            column: [],
            goodList: [],
            categoryList: [],
            show: false,
            listIndex: '',
            categoryId: '',
            suppliesId: '',
            goodsName: '',
            goodsUnit: '',
            unitPrice: '',
            goodsAmount: '',
            remark: '',
            detailId: this.$route.params.id || '',
            keyword: '',
            goodsShow: false,
            loading: false,
            showCategoryPicker: false,
            categoryName: ''
        }
    },

    created() {
        if (this.detailId) {
            this.getDetail()
        } else {
            this.initData()
        }
    },

    methods: {
        initData() {
            const params = {
                openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId
            }
            getCategoryList(params)
                .then(res => {
                    if (res.code === 200) {
                        this.categoryList = res.data.categoryList
                    } else {
                        Toast.fail(res.message || '获取类型列表失败')
                    }
                })
                .catch(err => {
                    console.error(err)
                    Toast.fail('获取类型列表失败')
                })
        },

        getDetail() {
            getApplyRecordDetails(this.detailId)
                .then(res => {
                    if (res.code === 200) {
                        this.column = res.data.map(item => ({
                            categoryId: item.categoryId,
                            categoryName: item.categoryName,
                            suppliesId: item.suppliesId,
                            goodsUnit: item.goodsUnit,
                            unitPrice: item.unitPrice,
                            goodsAmount: item.goodsAmount,
                            amount: item.amount,
                            remark: item.remark,
                        }))
                        this.calculateTotal()
                    } else {
                        Toast.fail(res.message || '获取详情失败')
                    }
                })
                .catch(err => {
                    console.error(err)
                    Toast.fail('获取详情失败')
                })
        },

        addTap() {
            this.show = true
            this.listIndex = ''
            this.resetForm()
        },

        resetForm() {
            this.categoryId = ''
            this.categoryName = ''
            this.suppliesId = ''
            this.goodsName = ''
            this.goodsUnit = ''
            this.unitPrice = ''
            this.goodsAmount = ''
            this.remark = ''
        },

        deleteTap(index) {
            this.column.splice(index, 1)
            this.calculateTotal()
        },

        editTap(index) {
            const item = this.column[index]
            this.listIndex = index
            this.categoryId = item.categoryId
            this.categoryName = item.categoryName
            this.suppliesId = item.suppliesId
            this.goodsName = item.goodsName
            this.goodsUnit = item.goodsUnit
            this.unitPrice = item.unitPrice
            this.goodsAmount = item.goodsAmount
            this.remark = item.remark
            this.show = true
        },

        calculateTotal() {
            this.totalMoney = this.column.reduce((total, item) => {
                return total + Number(item.amount)
            }, 0).toFixed(2)
        },

        onCategoryConfirm(value) {
            this.categoryName = value.categoryName
            this.categoryId = value.id
            this.showCategoryPicker = false
            this.getGoodsByCategory()
        },
        showGoodsDialog() {
            if (!this.categoryId) {
                Toast('请先选择类型')
                return
            }
            this.getGoodsByCategory()
        },
        onSearch() {
            if (this.searchTimer) {
                clearTimeout(this.searchTimer)
            }
            this.searchTimer = setTimeout(() => {
                this.getGoodsByCategory()
            }, 300)
        },

        getGoodsByCategory() {
            const params = {
                categoryId: this.categoryId,
                openSessionId: JSON.parse(localStorage.getItem('user'))?.openSessionId
            }

            getGoodsList(params)
                .then(res => {
                    if (res.code === 200) {
                        this.goodList = res.data || []
                        this.goodsShow = true

                    } else {
                        Toast.fail(res.message || '获取商品列表失败')
                    }
                })
                .catch(err => {
                    console.error(err)
                    Toast.fail('获取商品列表失败')
                })
        },

        goodsSelectTap(item) {
          
            this.goodsName = item.goodsName
            this.goodsUnit = item.goodsUnit
            this.suppliesId = item.id
            this.unitPrice = item.unitPrice
            this.goodsShow = false
            
        },

        submitDialogTap() {
            if (!this.unitPrice || !this.goodsAmount) {
                Toast('请填写完整信息')
                return
            }

            const amount = (Number(this.unitPrice) * Number(this.goodsAmount)).toFixed(2)
            const item = {
                categoryId: this.categoryId,
                categoryName: this.categoryName,
                suppliesId: this.suppliesId,
                goodsName: this.goodsName,
                goodsUnit: this.goodsUnit,
                unitPrice: this.unitPrice,
                goodsAmount: this.goodsAmount,
                amount,
                remark: this.remark
            }
          
            if (this.listIndex !== '') {
              
                this.column[this.listIndex] = item
            } else {
                this.column.push(item)
            }
        
            this.calculateTotal()
            this.show = false
            this.resetForm()
        },

        cancleDialogTap() {
            this.show = false
            this.resetForm()
        },

        submitClick() {
            if (this.column.length === 0) {
                Toast('至少填写一条进货物品信息')
                return
            }

            this.loading = true
            const params = {
                applyRecordDetailsList: this.column.map(item => ({
                    categoryId: item.categoryId,
                    categoryName:item.categoryName,
                    suppliesId: item.suppliesId,
                    unitPrice: item.unitPrice,
                    goodsName: item.goodsName,
                    goodsUnit: item.goodsUnit,
                    goodsAmount: item.goodsAmount,
                    amount: item.amount,
                    remark: item.remark
                })),
                amount: this.totalMoney
            }
            if(this.detailId){
                console.log(params);
                purchaseReApply(params).then(res => {
                    if (res.code === 200) {
                        Toast.success(res.message)
                        this.$router.back()
                    } else {
                        Toast.fail(res.message)
                    }
                })
                .catch(err => {
                    console.error(err)
                    Toast.fail('提交失败')
                })
                .finally(() => {
                    this.loading = false
                })
            }else{
                console.log(this.column);
                submitPurchase(params).then(res => {
                    if (res.code === 200) {
                        Toast.success(res.message)
                        this.$router.back()
                    } else {
                        Toast.fail(res.message)
                    }
                })
                .catch(err => {
                    console.error(err)
                    Toast.fail('提交失败')
                })
                .finally(() => {
                    this.loading = false
                })
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.purchase-container {
    min-height: 100vh;
    background-color: #f5f5f5;
    padding: 20px;

    .goods-list-container {
        height: 350px;
        overflow-y: auto;
    }

    .p-item {
        background: #fff;
        border: 1px solid #ddd;
        border-radius: 8px;
        margin-bottom: 15px;
        padding: 15px;
        position: relative;

        .p-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }

        .p-text {
            padding: 10px 0;

            .p-text-line {
                margin-bottom: 5px;
                color: #666;

                &.flex {
                    display: flex;
                    justify-content: space-between;
                }
            }
        }

        .delbtn {
            position: absolute;
            right: 75px;
            bottom: 15px;
        }

        .editbtn {
            position: absolute;
            right: 15px;
            bottom: 15px;
        }
    }

    .p-add {
        height: 45px;
        background: #f3f6fe;
        border: 1px solid #4086FF;
        border-radius: 4px;
        color: #4086FF;
        font-size: 32px;
        text-align: center;
        line-height: 45px;
        margin: 20px 0;
    }

    .bottom-btn {
        margin-top: 20px;

        .total {
            color: #4086FF;
            font-weight: bold;
        }

        .submit-btn {
            margin-top: 15px;
        }
    }
}
</style>